package leveldesigner.util;

import java.util.ArrayList;

public class Matrix <E>{
	private int width;
	private int height;
	private ArrayList <ArrayList<E>> matrix;
	
	public Matrix(){
		width = 5;
		height = 5;
		matrix = new ArrayList<ArrayList<E>>(height);
		for (int i = 0; i< height; i++){
			ArrayList<E> row = new ArrayList<E>(width);
			matrix.add(row);
		}
	}
	
	public Matrix(int width, int height){
		this.width = width;
		this.height = height;
		matrix = new ArrayList<ArrayList<E>>(height);
		for (int i = 0; i< height; i++){
			ArrayList<E> row = new ArrayList<E>(width);
			matrix.add(row);
		}
	}
	public void setSize(int width, int height){
		this.setWidth(width);
		this.setHeight(height);
	}
	public void setElementAt (int x, int y, E element){ 
		matrix.get(y).add(x, element);
	}
	public E getElementAt(int x, int y){
		return matrix.get(y).get(x);
	}
	public void setHeight(int height) {
		// Nothing happens if current height = new height
		if (this.height == height){
			return;
		}
		// Map height will be reduced
		else if (this.height > height){
			for (int i = 0; i< this.height-height; i++){
				matrix.remove(this.height- i);
			}
			matrix.trimToSize();
		}
		// Map height will be increased
		else{
			matrix.ensureCapacity(height);
		}
		this.height = height;
	}
	public int getHeight() {
		return height;
	}
	public void setWidth(int width) {
		// Nothing happens if current width = new width
		if (this.width == width){
			return;
		}
		// Map will be reduced
		else if (this.width > width){
			for (ArrayList<E>row:matrix){
				for (int i = 0; i<this.width - width; i++){
					row.remove(width-i);
				}
				row.trimToSize();
			}
		}
		// Map will be increased
		else{
			for (ArrayList<E>row:matrix){
				row.ensureCapacity(width);
			}
		}
		this.width = width;
	}
	public int getWidth() {
		return width;
	}
}
